import axios from 'axios'
import { ElMessage } from 'element-plus';
import router from '@/router/index'

//创建axios实例对象
const request = axios.create({
  baseURL: '/api',
  timeout: 600000
})

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    let loginUser = JSON.parse(localStorage.getItem('loginUser'))
    if (loginUser) {
      config.headers.token = loginUser.token
    }
    return config;
  }, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

//axios的响应 response 拦截器
request.interceptors.response.use(
  (response) => { //成功回调
    return response.data
  },
  (error) => { //失败回调
    if (error.response.status === 401) {
      ElMessage.error('登录超时,请重新登录！')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default request